﻿using System;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Text.RegularExpressions;
using Koonsoft.HYCRM.DAL;
using Koonsoft.HYCRM.Model;
using log4net;

namespace Koonsoft.HYCRM.BLL
{
    [DataObject]
    public class OrderBLL
    {
        private ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private OrderDAL _dal = null;

        private static readonly object Locker = new object();

        protected OrderDAL DAL
        {
            get
            {
                if (_dal == null)
                {
                    _dal = new OrderDAL();
                }

                return _dal;
            }
        }

        /// <summary>
        /// 生成订单
        /// </summary>
        /// <param name="order"></param>
        public bool CreateOrder(OrderInfo order, out string orderID, out string msg)
        {
            orderID = string.Empty;
            msg = string.Empty;

            try
            {
                #region 检查是否有同英文名同注册地的公司在同一天已办理了同类型的业务
                if (OrderDAL.CheckOrderExists(order.EnglishCompanyName, order.RegisterRegionID,
                                      order.OrderTime, order.DelegateTypeID))
                {
                    msg = "订单生成失败，已有同英文名同注册地的公司在同一天已办理了同类型的业务";

                    return false;
                }
                #endregion

                #region 存入数据库前进行DES加密
                if (!string.IsNullOrEmpty(order.Address))
                {
                    order.Address = EncryptHelper.Encrypt(order.Address, "3.141592");
                }
                if (!string.IsNullOrEmpty(order.Telephone))
                {
                    order.Telephone = EncryptHelper.Encrypt(order.Telephone, "3.141592");
                }
                if (!string.IsNullOrEmpty(order.Mobile))
                {
                    order.Mobile = EncryptHelper.Encrypt(order.Mobile, "3.141592");
                }
                #endregion
            }
            catch (Exception ex)
            {
                logger.Error("报单参数校验不通过", ex);

                msg = ex.Message;
                return false;
            }

            try
            {
                lock (Locker)
                {
                    var sb = new StringBuilder();
                    sb.Append(String.Format("{0:yyMMdd}", DateTime.Today));
                    string sequence = new UtilityBLL().GetRegularDateVal("OrderNo", 4,
                                                                   String.Format("{0:yyyyMMdd}", DateTime.Today));
                    sb.Append(sequence);
                    order.OrderID = sb.ToString();
                    orderID = sb.ToString();
                }

                if (!string.IsNullOrEmpty(orderID))
                {
                    DAL.CreateOrder(order);
                }
            }
            catch (Exception ex)
            {
                orderID = string.Empty;

                logger.Error("订单生成异常", ex);
            }

            return true;
        }

        /// <summary>
        /// 订单日报表
        /// </summary>
        /// <param name="branchName"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="delegateName"></param>
        /// <param name="empolyeeID"></param>
        /// <param name="regionName"></param>
        /// <returns></returns>
        public DataTable GetDailySheet(string branchName, string startTime, string endTime, string delegateName, string regionName, int empolyeeID)
        {
            return DAL.GetDailySheet(branchName, startTime, endTime, delegateName, regionName, empolyeeID);
        }

        /// <summary>
        /// 根据订单编号查公司
        /// </summary>
        /// <param name="orderID"></param>
        /// <returns></returns>
        public string GetCompanySerialNumberByOrderID(string orderID)
        {
            return DAL.GetCompanySerialNumberByOrderID(orderID);
        }

        /// <summary>
        /// 获取订单编号
        /// </summary>
        /// <param name="orderID"></param>
        /// <returns></returns>
        public OrderInfo GetOrderInfoByOrderID(string orderID)
        {
            var orderInfo = DAL.GetOrderInfoByOrderID(orderID);

            if (orderInfo == null)
            {
                return null;
            }

            try
            {
                // 对加密数据进行解密
                if (!string.IsNullOrEmpty(orderInfo.Telephone.Trim()))
                {
                    orderInfo.Telephone = EncryptHelper.Decrypt(orderInfo.Telephone, "3.141592");
                }

                if (!string.IsNullOrEmpty(orderInfo.Mobile.Trim()))
                {
                    orderInfo.Mobile = EncryptHelper.Decrypt(orderInfo.Mobile, "3.141592");
                }

                if (!string.IsNullOrEmpty(orderInfo.Address.Trim()))
                {
                    orderInfo.Address = EncryptHelper.Decrypt(orderInfo.Address, "3.141592");
                }

                // 补充订单信息
                orderInfo.DelegateName = new DelegateBLL().GetDelegateNameByDelegateType(orderInfo.DelegateTypeID);

            }
            catch (Exception ex)
            {
                logger.Error("获取订单信息失败", ex);
            }

            return orderInfo;
        }

        /// <summary>
        /// 按员工统计订单
        /// </summary>
        /// <returns></returns>
        public DataTable StatisticOrdersGroupByEmpolyee(string startTime, string endTime)
        {
            return DAL.StatisticOrdersGroupByEmpolyee(startTime, endTime);
        }


        /// <summary>
        /// 按分行统计订单数
        /// </summary>
        /// <returns></returns>
        public DataTable StatisticOrdersGroupByBranch(string startTime, string endTime)
        {
            return DAL.StatisticOrdersGroupByBranch(startTime, endTime);
        }

        /// <summary>
        /// 供总编处理的订单
        /// </summary>
        /// <returns></returns>
        public DataTable GetHongKongFileEditorOrders()
        {
            return DAL.GetHongKongFileEditorOrders();
        }

        /// <summary>
        /// 供银行助理处理的订单
        /// </summary>
        /// <returns></returns>
        public DataTable GetHongKongFileHelperOrders()
        {
            return DAL.GetHongKongFileHelperOrders();
        }

        /// <summary>
        /// 供银行助理处理的订单
        /// </summary>
        /// <returns></returns>
        public DataTable GetHongKongFileHelperOrders(int delegateID, int regionID, int branchID, string empolyeeName)
        {
            return DAL.GetHongKongFileHelperOrders(delegateID, regionID, branchID, empolyeeName);
        }

        public DataTable GetHongKongFileHelperOrdersForAuditors()
        {
            return DAL.GetHongKongFileHelperOrders().Select("业务类型='核数'").CopyToDataTable();
        }

        public DataTable GetAuditorsForUser(string loginName)
        {
            return DAL.GetAuditorsForUser(loginName);
        }

        /// <summary>
        /// 供其它（非香港）文件处理的订单
        /// </summary>
        /// <returns></returns>
        public DataTable GetOtherRegionFileHandlerOrders()
        {
            return DAL.GetOtherRegionFileHandlerOrders();
        }

        /// <summary>
        /// 获取总行等待快递的订单
        /// </summary>
        /// <returns></returns>
        public DataTable GetDeliverOrders(int empolyeeID, int ordermonth, int regionID, int branchID, int delegateID)
        {
            return DAL.GetDeliverOrders(empolyeeID, ordermonth, regionID, branchID, delegateID);
        }

        /// <summary>
        /// 获取等待分行快递核对全款的订单
        /// </summary>
        /// <returns></returns>
        public DataTable GetAuditOrders(int empolyeeID)
        {
            return DAL.GetAuditOrders(empolyeeID);
        }

        /// <summary>
        /// 改变订单状态
        /// </summary>
        /// <param name="orderID"></param>
        /// <param name="orderStatus"></param>
        public void ChangeOrderStatusByOrderID(string orderID, OrderStatus orderStatus)
        {
            DAL.ChangeOrderStatusByOrderID(orderID, orderStatus);
        }

        /// <summary>
        /// 根据订单号获取订单总入账金额
        /// </summary>
        /// <param name="orderID"></param>
        /// <returns></returns>
        public int GetIncomeByOrderID(string orderID)
        {
            return DAL.GetIncomeByOrderID(orderID);
        }

        /// <summary>
        /// 获取最近一次报单是不是报的找单
        /// </summary>
        /// <param name="companyID"></param>
        /// <returns></returns>
        public bool GetLastOrderInfoByCompanyID(string companyID)
        {
            return DAL.GetLastOrderInfoByCompanyID(companyID);
        }

        /// <summary>
        /// 校验报单前的资格认证
        /// </summary>
        /// <param name="orderinfo"></param>
        /// <returns></returns>
        public bool VerifyOrderData(OrderInfo orderinfo, out string msg)
        {
            msg = string.Empty;

            try
            {
                #region 检查报单参数是否符合规范

                // 检查英文公司名中是否含有中文
                if (Regex.Match(orderinfo.EnglishCompanyName, @"[\u4e00-\u9fa5]").Success)
                {
                    msg = "公司英文名中不能包含中文，请重新输入";
                    return false;
                }

                // 检查分行和业务类型是否选择正确
                if (orderinfo.BranchID == 999)
                {
                    msg = "错误的分行代码，请重新选择";
                    return false;
                }

                if (orderinfo.DelegateTypeID == 999)
                {
                    msg = "错误的业务类型，请重新选择";
                    return false;
                }


                //检查客户的电话号码是否正确
                if (!string.IsNullOrEmpty(orderinfo.Telephone))
                {
                    if (!Regex.Match(orderinfo.Telephone, @"^(\(\d{3,5}\)|\d{3,5}-)?\d{7,15}$").Success)
                    {
                        msg = "电话号码只能为0755-8888888类似格式";
                        return false;
                    }
                }

                // 检查客户的手机号码是否正确
                if (!string.IsNullOrEmpty(orderinfo.Mobile))
                {
                    if (!Regex.Match(orderinfo.Mobile, @"^\d{11}$").Success)
                    {
                        msg = "手机号码必须为11位数字";
                        return false;
                    }
                }


                #endregion

                #region 检查客户的联系方式是否填写了三项或三项以上

                int i = 0;

                if (!string.IsNullOrEmpty(orderinfo.Telephone))
                {
                    i = i + 1;
                }

                if (!string.IsNullOrEmpty(orderinfo.Mobile))
                {
                    i = i + 1;
                }

                if (!string.IsNullOrEmpty(orderinfo.Address))
                {
                    i = i + 1;
                }

                if (!string.IsNullOrEmpty(orderinfo.Email))
                {
                    i = i + 1;
                }

                if (!string.IsNullOrEmpty(orderinfo.IM))
                {
                    i = i + 1;
                }

                if (!string.IsNullOrEmpty(orderinfo.Fax))
                {
                    i = i + 1;
                }

                if (i < 3)
                {
                    msg = "客户的联系方式至少需要填写3项或3项以上";
                    return false;
                }

                #endregion

                #region 检查是否委托类型不是注册但未填写公司ID

                if (string.IsNullOrEmpty(orderinfo.CompanyID) && orderinfo.DelegateTypeID != 3)
                {
                    msg = "非注册类型的业务必须要填写公司ID";
                    return false;
                }

                #endregion

                #region 检查是否有同英文名同注册地的公司在同一天已办理了同类型的业务

                if (OrderDAL.CheckOrderExists(orderinfo.EnglishCompanyName, orderinfo.RegisterRegionID,
                                              DateTime.Now, orderinfo.DelegateTypeID))
                {
                    msg = "该公司已在同一天办理了同类型的业务，不能重复报单。";
                    return false;
                }

                #endregion

                #region 如果为丢单，则必须该公司ID所办的最近一次业务类型不是丢单

                if (orderinfo.DelegateTypeID == 52)
                {
                    if (new OrderBLL().GetLastOrderInfoByCompanyID(orderinfo.CompanyID))
                    {
                        msg = "该公司已被其他同事作为丢单录入成功";
                        return false;
                    }
                }

                #endregion

                #region 如果为找单，则必须在数据库中无此公司记录

                if (orderinfo.DelegateTypeID == 34)
                {
                    if (new CompanyBLL().GetCompanyInfoByCompanyIDAndRegionID(orderinfo.CompanyID, orderinfo.RegisterRegionID.ToString()) != null)
                    {
                        msg = "该公司已在公司数据库中了";

                        return false;
                    }
                }

                #endregion

                return true;
            }
            catch (Exception ex)
            {
                logger.Error("报单资格认证失败", ex);
                return false;
            }
        }


        /// <summary>
        /// 获取年检待办表
        /// </summary>
        /// <returns></returns>
        public DataTable GetYearAuditRefrence()
        {
            return DAL.GetYearAuditRefrence();
        }

        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="orderID"></param>
        /// <param name="operatorID"></param>
        /// <param name="remark"></param>
        public void CancelOrderByOperator(string orderID, int operatorID, string remark)
        {
            DAL.CancelOrderByOperator(orderID, operatorID, remark);
        }

        /// <summary>
        /// 获取订单扩展信息
        /// </summary>
        /// <param name="orderId"></param>
        public OrderExpansion GetOrderExpansion(string orderId)
        {
            return DAL.GetOrderExpansion(orderId);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="orderID"></param>
        /// <param name="Remark"></param>
        public void UpdateOrderExpansionRemark(string orderID,string Remark)
        {
            DAL.UpdateOrderExpansionRemark(orderID, Remark);
        }
    }
}
